package com.cunshe.service;

import com.cunshe.dao.MenuDao;
import com.cunshe.domain.Menu;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.Date;
import java.util.List;

/**
 * 菜单
 * @author xiao
 */
@Service
public class MenuService {

    @Autowired
    private MenuDao menuDao;

    /** 新增 */
    @Transactional(rollbackFor = Exception.class)
    public int insert(Menu record) {
        return menuDao.insert(record);
    }

    /** 删除 */
    @Transactional(rollbackFor = Exception.class)
    public int delete(Long id) {
        if(id == 5){
            return 0;
        }
        List<Menu> list = list(Menu.builder().build().setParentId(id));
        if(!CollectionUtils.isEmpty(list)){
            for (Menu menu : list) {
                menuDao.delete(menu.getId());
            }
        }
        return menuDao.delete(id);
    }

    /** 修改 */
    @Transactional(rollbackFor = Exception.class)
    public int update(Menu record) {
        record.setUpdatetime(new Date());
        return menuDao.update(record);
    }

    /** 查询列表 */
    public List<Menu> all() {
        return list(Menu.builder().build());
    }

    /** 查询列表 */
    public List<Menu> list(Menu record) {
        PageHelper.orderBy(" sort_num DESC, id ASC ");
        return menuDao.list(record);
    }

}